package com.kl.component.shiro;

import com.kl.common.util.EncryptionUtil;
import com.kl.modular.system.dao.bo.SystemAdminBo;
import com.kl.modular.system.dao.bo.SystemAdminRoleBo;
import com.kl.modular.system.dao.model.SystemAdmin;
import com.kl.modular.system.dao.model.SystemAdminRole;
import com.kl.modular.system.dao.model.SystemAuthResource;
import com.kl.modular.system.dao.model.SystemRole;
import com.kl.modular.system.service.api.ISystemAdminRoleService;
import com.kl.modular.system.service.api.ISystemAdminService;
import com.kl.modular.system.service.api.ISystemRoleService;
import com.kl.modular.system.service.constant.SystemConStant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * 系统登陆管理员 会话保存
 * @author zjb
 * @date 2015-1-4
 */
@Component
public class SysmanCredentialsMatcher extends SimpleCredentialsMatcher {
	
	private static final Logger logger = LoggerFactory.getLogger(SysmanCredentialsMatcher.class);

	public final static String ACCOUNT_TYPE_PUBLIC_SECURITY = "public_security";// 公安
	public final static String ACCOUNT_TYPE_ENTERPRISE = "enterprise";// 企业
	
	@Autowired
	private ISystemAdminService systemAdminService;
	
	@Autowired
	private ISystemAdminRoleService systemAdminRoleService;
	
	@Autowired
	private ISystemRoleService systemRoleService;

	/**
	 * 统一验证
	 * @param authcToken
	 * @param info
	 * @return
	 */
 	@Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info){
		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
		if(token == null || StringUtils.isEmpty(token.getType())){
			throw new AuthenticationException("登陆验证有误");
		}
		if(StringUtils.equals(token.getType(), CaptchaUsernamePasswordToken.TYPE_SYS)){
			return sysuserCredentialsMatch(token);
		}
		throw new AuthenticationException("登陆验证有误");
    }

	/**
	 * 系统管理员验证
	 * @param token
	 * @return
	 */
	public boolean sysuserCredentialsMatch(CaptchaUsernamePasswordToken token){
		SystemAdminBo systemAdminBo = new SystemAdminBo();
		systemAdminBo.setAdminUserName(token.getUsername());
		SystemAdmin systemAdmin = systemAdminService.getSystemAdminByBo(systemAdminBo);
		if (systemAdmin == null) {
			return false;
		}
		logger.info("密码匹配，用户：" + token.getUsername());
		boolean pass = EncryptionUtil.decrypt(String.valueOf(token.getPassword()), systemAdmin.getSystemSalt(), systemAdmin.getSystemPassword());
		Session session = SecurityUtils.getSubject().getSession();
		if(!pass){
			logger.info("密码匹配错误，用户：" + token.getUsername());
			return false;
		}
		SystemAdminRoleBo adminRoleBo = new SystemAdminRoleBo();
		adminRoleBo.setAdminCode(systemAdmin.getSystemCode());
		List<SystemAdminRole> adminRoleList = systemAdminRoleService.getListByBo(adminRoleBo);
		if(adminRoleList == null||adminRoleList.size() == 0){
			adminRoleList = new ArrayList<SystemAdminRole>();
		}
		StringBuffer roleIdBuffer = new StringBuffer();
		StringBuffer roleNameBuffer = new StringBuffer();
		StringBuffer roleShiroBuffer = new StringBuffer();
		for (int i = 0; i < adminRoleList.size(); i++) {
			SystemAdminRole adminRole = adminRoleList.get(i);
			if(adminRole == null || StringUtils.isEmpty(adminRole.getRoleCode())){
				continue;
			}
			SystemRole systemRole = null;
			try {
				systemRole = systemRoleService.getSystemRoleByCode(adminRole.getRoleCode());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(systemRole == null){
				continue;
			}
			if(!StringUtils.isEmpty(roleIdBuffer.toString())){
				roleIdBuffer.append(",");
			}
			if(!StringUtils.isEmpty(roleNameBuffer.toString())){
				roleNameBuffer.append(",");
			}
			if(!StringUtils.isEmpty(roleShiroBuffer.toString())){
				roleShiroBuffer.append(",");
			}
			roleShiroBuffer.append(systemRole.getRoleShrioCode());
			roleIdBuffer.append(systemRole.getRoleCode());
			roleNameBuffer.append(systemRole.getRoleName());
		}
		if(StringUtils.isEmpty(roleIdBuffer.toString())){
			logger.info("找不到角色，用户：" + token.getUsername());
			throw new RoleNotHaveAuthException("该用户没有任何角色权限，无法登陆");
		}
		AuthorityUser authorityUser = new AuthorityUser();
		authorityUser.setAdminId(systemAdmin.getSystemCode());
		authorityUser.setRoleCodes(roleIdBuffer.toString());
		authorityUser.setRoleShiroCode(roleShiroBuffer.toString());
		authorityUser.setRoleNames(roleNameBuffer.toString());
		authorityUser.setUserName(systemAdmin.getSystemUserName());
		authorityUser.setId(systemAdmin.getId());
		authorityUser.setUserType(SystemAuthResource.AUTH_MODULE_SYS);
		session.setAttribute(SystemConStant.SESSION_USER_KEY, authorityUser);
		return true;
	}

}